package org.jeecg.modules.charge.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.MD5Utils;
import org.jeecg.common.util.StringUtils;
import org.jeecg.config.GetRequestJsonUtils;
import org.jeecg.config.JsonMapper;
import org.jeecg.config.Sm4Util;
import org.jeecg.modules.charge.entity.ChargePayNotify;
import org.jeecg.modules.charge.mapper.ComConfigMapper;
import org.jeecg.modules.charge.service.IChargeBillsOrderService;
import org.jeecg.modules.charge.service.IChargePayConfigService;
import org.jeecg.modules.charge.service.IChargeTypeService;
import org.jeecg.modules.charge.service.impl.ChargeInvoiceRequestServiceImpl;
import org.jeecg.modules.charge.vo.AppPayQuery;
import org.jeecg.modules.charge.vo.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;


/**
* @Description: 支付接口
* @Author:  Lee
* @Date:   2019-08-15
* @Version: V1.0
*/
@RestController
@RequestMapping("/b/charge")
@Api(tags="支付接口")
@Slf4j
public class ChargePayController {
    @Autowired
    private IChargeBillsOrderService chargeBillsOrderService;
    @Autowired
    private IChargePayConfigService chargePayConfigService;
    @Autowired
    private IChargeTypeService chargeTypeService;
//    @Autowired
//    private IBaseRoomService baseRoomService;
    @Autowired
    private ComConfigMapper comConfigMapper;
    @Autowired
    private ChargeInvoiceRequestServiceImpl invoiceReqService;

    @Value("${payquery.url}")
    private String payQueryUrl;

    @Value("${pay.fftEncryptKey}")
    private String fftEncryptKey; //付费通加密key

    //支付回调
    @RequestMapping(value = "/payCallBack", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("付费通回调接口")
    public String payCallBack(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            JSONObject jsonObject = GetRequestJsonUtils.getRequestJsonObject(request,fftEncryptKey);
            log.info("付费通回调接口参数：{}",jsonObject);
            ChargePayNotify stu= JSON.parseObject(jsonObject.toJSONString(), ChargePayNotify.class);
            chargeBillsOrderService.chargePayNotify(stu);
            return Sm4Util.encryptEcb(fftEncryptKey,"200success");
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return Sm4Util.encryptEcb(fftEncryptKey,"error");
    }

    //支付回调
    @RequestMapping(value = "/payCEBCallBack")
    @ResponseBody
    @ApiOperation("光大回调接口")
    public void payCEBCallBack(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            BufferedReader reader = request.getReader();
            String json = reader.readLine();
            reader.close();
            net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(json);
            int code = jsonObject.getInt("code");
            int status = jsonObject.getInt("status");
            net.sf.json.JSONObject data = net.sf.json.JSONObject.fromObject(jsonObject.getString("data"));
            if (code == 0){
                ChargePayNotify stu = new ChargePayNotify();
                stu.setOrderId(data.getString("out_trade_no"));
                stu.setPaymentAmt(data.getString("amount"));
                stu.setPaymentTime(data.getString("payment_at"));
                stu.setTransNo(data.getString("transaction_number"));
                chargeBillsOrderService.chargePayNotify(stu);
            }
            Writer out = response.getWriter();
            Map<String, Object> map = new HashMap<String, Object>();
            if (code == 0 && status == 0) {
                map.put("status", 0);
                map.put("msg", "");
                map.put("code", 0);
            } else {
                map.put("status", 1);
                map.put("msg", "");
                map.put("code", 0);
            }
            out.write(JsonMapper.getInstance().toJson(map));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 根据交易订单号获取对应的账单，拉取对应缴费的账单详情
     * @param
     * @param
     * @return
     * @throws
     */
    @AutoLog(value = "查询所有项目接口")
    @ApiOperation(value="查询所有项目接口", notes="查询所有项目接口")
    @PostMapping(value = "/getStatusByOrder")
    public Result<String>  getStatusByOrder(AppPayQuery query, HttpServletResponse response) throws Exception{
        Result<String> res=new  Result<String>();
        try {
            Map<String, String> sendMap = new HashMap<String, String>();
            sendMap.put("channel_id", query.getChannelId()); //渠道号
            sendMap.put("trade_type", query.getTradeType());//光大线上支付 appoint-appH5/指定项目版，wechat/微信版，alipay/支付宝版
            sendMap.put("property", query.getProperty());
            sendMap.put("property_type", query.getPropertyType());
            sendMap.put("transaction_number", query.getTransactionNumber());
            //排序
            String url = StringUtils.formatUrlMap(sendMap, true, false);//排序后的参数
            //拼接
            url = url + "&79E622A4FA8FC46851DD290002917677";
            String sign = MD5Utils.getMD5(url);//加密出sign
            sendMap.put("sign", sign);
            ObjectMapper json = new ObjectMapper();
            String params = json.writeValueAsString(sendMap);
            //响应结果
            String reso = HttpUtils.myUrlPost(payQueryUrl, params);//请求生成订单接口
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> resultMap = mapper.readValue(reso, new TypeReference<Map<String, Object>>() {
            });//请求成功接口
            Map<String, Object> map = (Map<String, Object>) resultMap.get("data");
            //支付操作成功接口
            if (String.valueOf(resultMap.get("code")).equals("0")) {
                String result=map.get("trade_state").toString();
                if("SUCCESS".equals(result)) {
                    res.setCode(1);
                    res.setMessage("支付成功!");
                }else {
                    res.setCode(0);
                    res.setMessage("支付失败!");
                }

            }
        }catch (Exception ex) {
            ex.printStackTrace();
            res.setCode(0);
            res.setMessage("请求银行支付接口失败，请稍后再试!");
        }
        return res;
    }

}
